package com.amit.servlet;

import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailService {
	
	private static String UNAME="amitjava534@gmail.com";
	private static String PASSWORD="ashayadav2";

	public static void sendMail(String em, String sub, String body) 
	{
		
		try
		{
			Message msg=getMessageForMail();
			msg.setSubject(sub);
			msg.setFrom(new InternetAddress(UNAME,"amit yadav"));
			msg.setRecipient(Message.RecipientType.TO,new InternetAddress(em));
			msg.setRecipient(Message.RecipientType.BCC, new InternetAddress("amityadav10603@gmail.com"));
			msg.setSentDate(new Date());
			msg.setContent(body,"text/html");
			Transport.send(msg);
		}
		catch (Exception e) {
			
			e.printStackTrace();
			
		}
		
	}

	private static Message getMessageForMail() {
		
		Authenticator auth=new MyPasswordAuthenicator();
		Properties p=new Properties();
		p.put("mail.smtp.host", "smtp.gmail.com");
		p.put("mail.smtp.socketFactory.port", "465");
		p.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		p.put("mail.smtp.auth", "true");
		p.put("mail.smtp.port", "465");
		
		Session sess=Session.getInstance(p,auth);
		Message msg=new MimeMessage(sess);
		
		return msg;
	}
	

	static class MyPasswordAuthenicator extends Authenticator {
		
		protected javax.mail.PasswordAuthentication getPasswordAuthentication()
		{
			System.out.println("\n ..getPasswordAuthentication called");
			
			return new javax.mail.PasswordAuthentication(UNAME, PASSWORD);
			
		}

	}

}
